#include "E_Pthread_Pool.h"
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <list>
#include "m_thread_cond.h"

//-------------------------E_PThread_Pool---------------------------------
E_PThread_Pool::E_PThread_Pool(unsigned int max, unsigned int min, long wait){

count = 0;
waitcount = 0;
mincount = min;
maxcount = max;
waitsec = wait;
Stop = false;

cond.lock();
	for(unsigned int i=0; i<mincount; i++){
		createThread();
	}
cond.unlock();
}
//----------------------------~E_PThread_Pool------------------------------
E_PThread_Pool::~E_PThread_Pool(){
	//destroyThread();
}
//----------------------------createThread------------------------------
void E_PThread_Pool::createThread(){
	pthread_t id;
	int ret = pthread_create(&id, NULL, taskThread, (void*)this);
	if(ret < 0){
	}
	else
	count++;
}
//-------------------------------taskThread---------------------------
void* E_PThread_Pool::taskThread(void *arg){
	pthread_detach(pthread_self());
	E_PThread_Pool *pool=(E_PThread_Pool*)arg;
	Task *t=NULL;
	while(1){
	std::cout<<"Enter Thread...."<<endl;
	pool->cond.lock();
	if(pool->taskList.empty()){//if list_task is empty,wait..timeout delete this thread 
/*	if(pool->Stop){//if stoped unlock and count-- delete this thread
	pool->count--;
	pool->cond.unlock();
	pthread_exit(NULL);
		}
*/
	pool->waitcount++;//waiting thread increase one
	bool bSignal = pool->cond.timewaitms(pool->waitsec);//waiting...
	std::cout<<"bSignal:"<<bSignal<<std::endl;
	pool->waitcount--;//delete or run_task or next waitint...
	if(bSignal && pool->count > pool->mincount){//delete extra thread//not siganl is 1
		pool->count--;
		pool->cond.unlock();
//		std::cout<<"Thread is destry"<<std::endl;
		pthread_exit(NULL);
	    }	
	}
	pool->cond.unlock();
	if(!pool->taskList.empty()){//get a task to run
		pool->taskCond.lock();
		t = pool->taskList.front();
		pool->taskList.pop_front();
		pool->taskCond.unlock();

		t->run();
//		std::cout<<"t->run"<<endl;
//		delete t;
		}
	}
	pthread_exit(NULL);
}
//---------------------addTask----------------------
void E_PThread_Pool::addTask(Task *task){

	if(Stop)  return;

	taskCond.lock();
		taskList.push_back(task);
	taskCond.unlock();

	cond.lock();
	if(waitcount){
		cond.signal();
	}
	else if(count < maxcount){
		createThread();
	}
	cond.unlock();

}